<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>认证调试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success { background-color: #d4edda; color: #155724; }
        .error { background-color: #f8d7da; color: #721c24; }
        .warning { background-color: #fff3cd; color: #856404; }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        textarea {
            width: 100%;
            height: 100px;
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .token-display {
            word-break: break-all;
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <h1>🔐 认证调试工具</h1>
    
    <div class="container">
        <h2>Token 状态检查</h2>
        <button onclick="checkToken()">检查 Token</button>
        <div id="tokenStatus"></div>
        <div id="tokenDisplay"></div>
    </div>
    
    <div class="container">
        <h2>API 连接测试</h2>
        <button onclick="testAuthAPI()">测试认证 API</button>
        <button onclick="testChatAPI()">测试聊天 API</button>
        <div id="apiStatus"></div>
    </div>
    
    <div class="container">
        <h2>手动登录</h2>
        <input type="text" id="username" placeholder="用户名" value="admin">
        <input type="password" id="password" placeholder="密码" value="123456">
        <button onclick="login()">登录</button>
        <div id="loginStatus"></div>
    </div>
    
    <div class="container">
        <h2>测试流式消息</h2>
        <input type="text" id="sessionId" placeholder="会话ID" value="990aee05-1445-4035-baae-6ff9e43f07c5">
        <textarea id="messageContent" placeholder="消息内容">测试消息</textarea>
        <input type="text" id="errorInfo" placeholder="错误信息" value="测试错误信息">
        <button onclick="testStreamMessage()">发送流式消息</button>
        <div id="streamStatus"></div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8000/api/v1';
        
        function log(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            const className = type === 'error' ? 'error' : type === 'success' ? 'success' : 'warning';
            element.innerHTML += `<div class="status ${className}">${new Date().toLocaleTimeString()}: ${message}</div>`;
        }
        
        function checkToken() {
            const token = localStorage.getItem('access_token');
            const tokenType = localStorage.getItem('token_type');
            const userInfo = localStorage.getItem('user_info');
            
            const statusEl = document.getElementById('tokenStatus');
            const displayEl = document.getElementById('tokenDisplay');
            
            statusEl.innerHTML = '';
            displayEl.innerHTML = '';
            
            if (token) {
                log('tokenStatus', `Token 存在，类型: ${tokenType || 'bearer'}`, 'success');
                
                // 解析JWT token
                try {
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    const exp = new Date(payload.exp * 1000);
                    const now = new Date();
                    
                    if (exp > now) {
                        log('tokenStatus', `Token 有效，过期时间: ${exp.toLocaleString()}`, 'success');
                    } else {
                        log('tokenStatus', `Token 已过期，过期时间: ${exp.toLocaleString()}`, 'error');
                    }
                    
                    log('tokenStatus', `用户: ${payload.sub}, 用户ID: ${payload.user_id}`, 'info');
                    
                    displayEl.innerHTML = `<div class="token-display">Token: ${token}</div>`;
                } catch (e) {
                    log('tokenStatus', 'Token 格式无效', 'error');
                }
                
                if (userInfo) {
                    log('tokenStatus', `用户信息: ${userInfo}`, 'info');
                }
            } else {
                log('tokenStatus', 'Token 不存在', 'error');
            }
        }
        
        async function testAuthAPI() {
            const token = localStorage.getItem('access_token');
            document.getElementById('apiStatus').innerHTML = '';
            
            if (!token) {
                log('apiStatus', '没有 Token，请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/auth/me`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    log('apiStatus', `认证成功: ${JSON.stringify(data)}`, 'success');
                } else {
                    const errorText = await response.text();
                    log('apiStatus', `认证失败 (${response.status}): ${errorText}`, 'error');
                }
            } catch (error) {
                log('apiStatus', `请求失败: ${error.message}`, 'error');
            }
        }
        
        async function testChatAPI() {
            const token = localStorage.getItem('access_token');
            document.getElementById('apiStatus').innerHTML = '';
            
            if (!token) {
                log('apiStatus', '没有 Token，请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/chat/test-auth`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    log('apiStatus', `聊天API认证成功: ${JSON.stringify(data)}`, 'success');
                } else {
                    const errorText = await response.text();
                    log('apiStatus', `聊天API认证失败 (${response.status}): ${errorText}`, 'error');
                }
            } catch (error) {
                log('apiStatus', `聊天API请求失败: ${error.message}`, 'error');
            }
        }
        
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            document.getElementById('loginStatus').innerHTML = '';
            
            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                if (response.ok) {
                    const data = await response.json();
                    localStorage.setItem('access_token', data.access_token);
                    localStorage.setItem('token_type', data.token_type);
                    if (data.user_info) {
                        localStorage.setItem('user_info', JSON.stringify(data.user_info));
                    }
                    log('loginStatus', '登录成功', 'success');
                    checkToken();
                } else {
                    const errorText = await response.text();
                    log('loginStatus', `登录失败 (${response.status}): ${errorText}`, 'error');
                }
            } catch (error) {
                log('loginStatus', `登录请求失败: ${error.message}`, 'error');
            }
        }
        
        async function testStreamMessage() {
            const token = localStorage.getItem('access_token');
            const sessionId = document.getElementById('sessionId').value;
            const messageContent = document.getElementById('messageContent').value;
            const errorInfo = document.getElementById('errorInfo').value;
            
            document.getElementById('streamStatus').innerHTML = '';
            
            if (!token) {
                log('streamStatus', '没有 Token，请先登录', 'error');
                return;
            }
            
            if (!sessionId || !messageContent || !errorInfo) {
                log('streamStatus', '请填写所有必需字段', 'error');
                return;
            }
            
            try {
                log('streamStatus', '开始发送流式消息...', 'info');
                
                const response = await fetch(`${API_BASE}/chat/sessions/${sessionId}/messages/stream`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream'
                    },
                    body: JSON.stringify({
                        content: messageContent,
                        content_type: 'text',
                        inputs: {
                            errorinfo: errorInfo
                        }
                    })
                });
                
                if (response.ok) {
                    log('streamStatus', '流式连接建立成功', 'success');
                    
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const chunk = decoder.decode(value);
                        log('streamStatus', `收到数据: ${chunk}`, 'info');
                    }
                } else {
                    const errorText = await response.text();
                    log('streamStatus', `流式消息失败 (${response.status}): ${errorText}`, 'error');
                }
            } catch (error) {
                log('streamStatus', `流式消息请求失败: ${error.message}`, 'error');
            }
        }
        
        // 页面加载时自动检查token
        window.onload = function() {
            checkToken();
        };
    </script>
</body>
</html>